home *** CD-ROM | disk | FTP | other *** search
/ Turnbull China Bikeride / Turnbull China Bikeride - Disc 2.iso / BARNET / INTERNET / PGP / PGP263I / pgp263i / src / c / idea < prev    next >
Encoding:
Text File  |  1997-05-23  |  18.5 KB  |  710 lines

  1. /*
  2.  *    idea.c - C source code for IDEA block cipher.
  3.  *      IDEA (International Data Encryption Algorithm), formerly known as
  4.  *      IPES (Improved Proposed Encryption Standard).
  5.  *      Algorithm developed by Xuejia Lai and James L. Massey, of ETH Zurich.
  6.  *      This implementation modified and derived from original C code
  7.  *      developed by Xuejia Lai.
  8.  *      Zero-based indexing added, names changed from IPES to IDEA.
  9.  *      CFB functions added.  Random number routines added.
  10.  *
  11.  *      Extensively optimized and restructured by Colin Plumb.
  12.  *
  13.  *      There are two adjustments that can be made to this code to
  14.  *      speed it up.  Defaults may be used for PCs.  Only the -DIDEA32
  15.  *      pays off significantly if selectively set or not set.
  16.  *      Experiment to see what works best for your machine.
  17.  *
  18.  *      Multiplication: default is inline, -DAVOID_JUMPS uses a
  19.  *              different version that does not do any conditional
  20.  *              jumps (a few percent worse on a SPARC), while
  21.  *              -DSMALL_CACHE takes it out of line to stay
  22.  *              within a small on-chip code cache.
  23.  *      Variables: normally, 16-bit variables are used, but some
  24.  *              machines (notably RISCs) do not have 16-bit registers,
  25.  *              so they do a great deal of masking.  -DIDEA32 uses "int"
  26.  *              register variables and masks explicitly only where
  27.  *              necessary.  On a SPARC, for example, this boosts
  28.  *              performace by 30%.
  29.  *
  30.  *      The IDEA(tm) block cipher is covered by patents held by ETH and a
  31.  *      Swiss company called Ascom-Tech AG.  The Swiss patent number is
  32.  *      PCT/CH91/00117, the European patent number is EP 0 482 154 B1, and
  33.  *      the U.S. patent number is US005214703.  IDEA(tm) is a trademark of
  34.  *      Ascom-Tech AG.  There is no license fee required for noncommercial
  35.  *      use.  Commercial users may obtain licensing details from Dieter
  36.  *      Profos, Ascom Tech AG, Solothurn Lab, Postfach 151, 4502 Solothurn,
  37.  *      Switzerland, Tel +41 65 242885, Fax +41 65 235761.
  38.  *
  39.  *      The IDEA block cipher uses a 64-bit block size, and a 128-bit key
  40.  *      size.  It breaks the 64-bit cipher block into four 16-bit words
  41.  *      because all of the primitive inner operations are done with 16-bit
  42.  *      arithmetic.  It likewise breaks the 128-bit cipher key into eight
  43.  *      16-bit words.
  44.  *
  45.  *      For further information on the IDEA cipher, see the book:
  46.  *        Xuejia Lai, "On the Design and Security of Block Ciphers",
  47.  *        ETH Series on Information Processing (ed. J.L. Massey) Vol 1,
  48.  *        Hartung-Gorre Verlag, Konstanz, Switzerland, 1992.  ISBN
  49.  *        3-89191-573-X.
  50.  *
  51.  *      This code runs on arrays of bytes by taking pairs in big-endian
  52.  *      order to make the 16-bit words that IDEA uses internally.  This
  53.  *      produces the same result regardless of the byte order of the
  54.  *      native CPU.
  55.  */
  56.  
  57. #include <string.h>
  58. #include "idea.h"
  59. #include "randpool.h"
  60.  
  61. #ifdef MACTC5
  62. #include <string.h>
  63. #define IDEA32
  64. #define SMALL_CACHE
  65. #define USE68ASM
  66. void ideaCipher(byte const inbuf[8], byte outbuf[8],
  67.                word16 const *key);
  68. #endif
  69.  
  70. #ifdef IDEA32            /* Use >16-bit temporaries */
  71. #define low16(x) ((x) & 0xFFFF)
  72. typedef unsigned int uint16;    /* at LEAST 16 bits, maybe more */
  73. #else
  74. #define low16(x) (x)        /* this is only ever applied to uint16's */
  75. typedef word16 uint16;
  76. #endif
  77.  
  78. #ifdef _GNUC_
  79. /* __const__ simply means there are no side effects for this function,
  80.  * which is useful info for the gcc optimizer
  81.  */
  82. #define CONST __const__
  83. #else
  84. #define CONST
  85. #endif
  86.  
  87. /*
  88.  * Multiplication, modulo (2**16)+1
  89.  * Note that this code is structured on the assumption that
  90.  * untaken branches are cheaper than taken branches, and the
  91.  * compiler doesn't schedule branches.
  92.  */
  93. #ifdef SMALL_CACHE
  94. #ifdef MACTC5
  95.  
  96. CONST static uint16
  97. mul(uint16 a, uint16 b) {
  98. asm {
  99.         move.w    a,d1
  100.         beq.s    @aeq0
  101.         move.w    b,d0
  102.         beq.s    @beq0
  103.         mulu.w    d0,d1    ; a = a * b
  104.         move.w    d1,d0    ; b = a
  105.         swap    d1        ; a = a >> 16
  106.         sub.w    d1,d0    ; b = b - a
  107.         bcc.s    @endit    ; b >= a?
  108.         addq.w    #1,d0    ; b < a : (b - a) + 1
  109.         bra.s    @endit
  110. @aeq0:    moveq    #1,d0
  111.         move.w    b,d1
  112.         sub.w    d1,d0    ; 1 - b
  113.         bra.s    @endit
  114. @beq0:    moveq    #1,d0
  115.         sub.w    d1,d0    ; 1 - a
  116.         }
  117. endit:    return;
  118. }
  119.  
  120. #else
  121.  
  122. CONST static uint16
  123.  mul(register uint16 a, register uint16 b)
  124. {
  125.     register word32 p;
  126.  
  127.     p = (word32) a *b;
  128.     if (p) {
  129.     b = low16(p);
  130.     a = p >> 16;
  131.     return (b - a) + (b < a);
  132.     } else if (a) {
  133.     return 1 - a;
  134.     } else {
  135.     return 1 - b;
  136.     }
  137. }                /* mul */
  138. #endif            /* MACTC5 */
  139. #endif            /* SMALL_CACHE */
  140.  
  141. /*
  142.  * Compute the multiplicative inverse of x, modulo 65537, using Euclid's
  143.  * algorithm. It is unrolled twice to avoid swapping the registers each
  144.  * iteration, and some subtracts of t have been changed to adds.
  145.  */
  146. CONST static uint16
  147.  mulInv(uint16 x)
  148. {
  149.     uint16 t0, t1;
  150.     uint16 q, y;
  151.  
  152.     if (x <= 1)
  153.     return x;        /* 0 and 1 are self-inverse */
  154.     t1 = 0x10001L / x;        /* Since x >= 2, this fits into 16 bits */
  155.     y = 0x10001L % x;
  156.     if (y == 1)
  157.     return low16(1 - t1);
  158.     t0 = 1;
  159.     do {
  160.     q = x / y;
  161.     x = x % y;
  162.     t0 += q * t1;
  163.     if (x == 1)
  164.         return t0;
  165.     q = y / x;
  166.     y = y % x;
  167.     t1 += q * t0;
  168.     } while (y != 1);
  169.     return low16(1 - t1);
  170. }                /* mukInv */
  171.  
  172. /* gjm:
  173.  * One version of Acorn's C compiler has a bug that prevents
  174.  * the following being compiled correctly. So it's hand-coded
  175.  * in s.ideaARM .
  176.  */
  177. #ifdef RISC_OS
  178. extern void ideaExpandKey(byte const *userkey, word16 * EK);
  179. #else
  180. /*
  181.  * Expand a 128-bit user key to a working encryption key EK
  182.  */
  183. static void ideaExpandKey(byte const *userkey, word16 * EK)
  184. {
  185.     int i, j;
  186.  
  187.     for (j = 0; j < 8; j++) {
  188.     EK[j] = (userkey[0] << 8) + userkey[1];
  189.     userkey += 2;
  190.     }
  191.     for (i = 0; j < IDEAKEYLEN; j++) {
  192.     i++;
  193.     EK[i + 7] = EK[i & 7] << 9 | EK[i + 1 & 7] >> 7;
  194.     EK += i & 8;
  195.     i &= 7;
  196.     }
  197. }                /* ideaExpandKey */
  198.  
  199. /* gjm:
  200.  * see immediately before function above
  201.  */
  202. #endif
  203.  
  204. /*
  205.  * Compute IDEA decryption key DK from an expanded IDEA encryption key EK
  206.  * Note that the input and output may be the same.  Thus, the key is
  207.  * inverted into an internal buffer, and then copied to the output.
  208.  */
  209. static void ideaInvertKey(word16 const *EK, word16 DK[IDEAKEYLEN])
  210. {
  211.     int i;
  212.     uint16 t1, t2, t3;
  213.     word16 temp[IDEAKEYLEN];
  214.     word16 *p = temp + IDEAKEYLEN;
  215.  
  216.     t1 = mulInv(*EK++);
  217.     t2 = -*EK++;
  218.     t3 = -*EK++;
  219.     *--p = mulInv(*EK++);
  220.     *--p = t3;
  221.     *--p = t2;
  222.     *--p = t1;
  223.  
  224.     for (i = 0; i < IDEAROUNDS - 1; i++) {
  225.     t1 = *EK++;
  226.     *--p = *EK++;
  227.     *--p = t1;
  228.  
  229.     t1 = mulInv(*EK++);
  230.     t2 = -*EK++;
  231.     t3 = -*EK++;
  232.     *--p = mulInv(*EK++);
  233.     *--p = t2;
  234.     *--p = t3;
  235.     *--p = t1;
  236.     }
  237.     t1 = *EK++;
  238.     *--p = *EK++;
  239.     *--p = t1;
  240.  
  241.     t1 = mulInv(*EK++);
  242.     t2 = -*EK++;
  243.     t3 = -*EK++;
  244.     *--p = mulInv(*EK++);
  245.     *--p = t3;
  246.     *--p = t2;
  247.     *--p = t1;
  248. /* Copy and destroy temp copy */
  249.     memcpy(DK, temp, sizeof(temp));
  250.     burn(temp);
  251. }                /* ideaInvertKey */
  252.  
  253. /*
  254.  * MUL(x,y) computes x = x*y, modulo 0x10001.  Requires two temps,
  255.  * t16 and t32.  x is modified, and must be a side-effect-free lvalue.
  256.  * y may be anything, but unlike x, must be strictly less than 65536
  257.  * even if low16() is #defined.
  258.  * All of these are equivalent - see which is faster on your machine
  259.  */
  260. #ifdef SMALL_CACHE
  261. #define MUL(x,y) (x = mul(low16(x),y))
  262. #else                /* !SMALL_CACHE */
  263. #ifdef AVOID_JUMPS
  264. #define MUL(x,y) (x = low16(x-1), t16 = low16((y)-1), \
  265.         t32 = (word32)x*t16 + x + t16, x = low16(t32), \
  266.         t16 = t32>>16, x = (x-t16) + (x<t16) + 1)
  267. #else                /* !AVOID_JUMPS (default) */
  268. #define MUL(x,y) \
  269.     ((t16 = (y)) ? \
  270.         (x=low16(x)) ? \
  271.             t32 = (word32)x*t16, \
  272.             x = low16(t32), \
  273.             t16 = t32>>16, \
  274.             x = (x-t16)+(x<t16) \
  275.         : \
  276.             (x = 1-t16) \
  277.     : \
  278.         (x = 1-x))
  279. #endif
  280. #endif
  281.  
  282. /* gjm:
  283.  * we have an ARM-coded implementation of ideaCipher, so
  284.  * don't want the following function defined here.
  285.  */
  286. #ifdef RISC_OS
  287. extern void ideaCipher(byte const inbuf[8], byte outbuf[8],
  288.                word16 const *key);
  289. #else
  290.  
  291. /*      IDEA encryption/decryption algorithm */
  292. /* Note that in and out can be the same buffer */
  293. #ifndef USE68ASM
  294. static void ideaCipher(byte const inbuf[8], byte outbuf[8],
  295.                word16 const *key)
  296. {
  297.     register uint16 x1, x2, x3, x4, s2, s3;
  298.     word16 *in, *out;
  299. #ifndef SMALL_CACHE
  300.     register uint16 t16;    /* Temporaries needed by MUL macro */
  301.     register word32 t32;
  302. #endif
  303.     int r = IDEAROUNDS;
  304.  
  305.     in = (word16 *) inbuf;
  306.     x1 = *in++;
  307.     x2 = *in++;
  308.     x3 = *in++;
  309.     x4 = *in;
  310. #ifndef HIGHFIRST
  311.     x1 = (x1 >> 8) | (x1 << 8);
  312.     x2 = (x2 >> 8) | (x2 << 8);
  313.     x3 = (x3 >> 8) | (x3 << 8);
  314.     x4 = (x4 >> 8) | (x4 << 8);
  315. #endif
  316.     do {
  317.     MUL(x1, *key++);
  318.     x2 += *key++;
  319.     x3 += *key++;
  320.     MUL(x4, *key++);
  321.  
  322.     s3 = x3;
  323.     x3 ^= x1;
  324.     MUL(x3, *key++);
  325.     s2 = x2;
  326.     x2 ^= x4;
  327.     x2 += x3;
  328.     MUL(x2, *key++);
  329.     x3 += x2;
  330.  
  331.     x1 ^= x2;
  332.     x4 ^= x3;
  333.  
  334.     x2 ^= s3;
  335.     x3 ^= s2;
  336.     } while (--r);
  337.     MUL(x1, *key++);
  338.     x3 += *key++;
  339.     x2 += *key++;
  340.     MUL(x4, *key);
  341.  
  342.     out = (word16 *) outbuf;
  343. #ifdef HIGHFIRST
  344.     *out++ = x1;
  345.     *out++ = x3;
  346.     *out++ = x2;
  347.     *out = x4;
  348. #else                /* !HIGHFIRST */
  349.     x1 = low16(x1);
  350.     x2 = low16(x2);
  351.     x3 = low16(x3);
  352.     x4 = low16(x4);
  353.     *out++ = (x1 >> 8) | (x1 << 8);
  354.     *out++ = (x3 >> 8) | (x3 << 8);
  355.     *out++ = (x2 >> 8) | (x2 << 8);
  356.     *out = (x4 >> 8) | (x4 << 8);
  357. #endif
  358. }                /* ideaCipher */
  359. #endif            /* USE68ASM */
  360.  
  361. /* gjm:
  362.  * see immediately above preceding function
  363.  */
  364. #endif
  365.  
  366. /*-------------------------------------------------------------*/
  367.  
  368. #ifdef TEST
  369.  
  370. #include <stdio.h>
  371. #include <time.h>
  372. /*
  373.  * This is the number of Kbytes of test data to encrypt.
  374.  * It defaults to 1 MByte.
  375.  */
  376. #ifndef BLOCKS
  377. #ifndef KBYTES
  378. #define KBYTES 1024
  379. #endif
  380. #define BLOCKS (64*KBYTES)
  381. #endif
  382.  
  383. int main(void)
  384. {                /* Test driver for IDEA cipher */
  385.     int i, j, k;
  386.     byte userkey[16];
  387.     word16 EK[IDEAKEYLEN], DK[IDEAKEYLEN];
  388.     byte XX[8], YY[8], ZZ[8];
  389.     clock_t start, end;
  390.     long l;
  391.  
  392.     /* Make a sample user key for testing... */
  393.     for (i = 0; i < 16; i++)
  394.     userkey[i] = i + 1;
  395.  
  396.     /* Compute encryption subkeys from user key... */
  397.     ideaExpandKey(userkey, EK);
  398.     printf("\nEncryption key subblocks: ");
  399.     for (j = 0; j < IDEAROUNDS + 1; j++) {
  400.     printf("\nround %d:   ", j + 1);
  401.     if (j < IDEAROUNDS)
  402.         for (i = 0; i < 6; i++)
  403.         printf(" %6u", EK[j * 6 + i]);
  404.     else
  405.         for (i = 0; i < 4; i++)
  406.         printf(" %6u", EK[j * 6 + i]);
  407.     }
  408.  
  409.     /* Compute decryption subkeys from encryption subkeys... */
  410.     ideaInvertKey(EK, DK);
  411.     printf("\nDecryption key subblocks: ");
  412.     for (j = 0; j < IDEAROUNDS + 1; j++) {
  413.     printf("\nround %d:   ", j + 1);
  414.     if (j < IDEAROUNDS)
  415.         for (i = 0; i < 6; i++)
  416.         printf(" %6u", DK[j * 6 + i]);
  417.     else
  418.         for (i = 0; i < 4; i++)
  419.         printf(" %6u", DK[j * 6 + i]);
  420.     }
  421.  
  422.     /* Make a sample plaintext pattern for testing... */
  423.     for (k = 0; k < 8; k++)
  424.     XX[k] = k;
  425.  
  426.     printf("\n Encrypting %d bytes (%ld blocks)...", BLOCKS * 16, BLOCKS);
  427.     fflush(stdout);
  428.     start = clock();
  429.     memcpy(YY, XX, 8);
  430.     for (l = 0; l < BLOCKS; l++)
  431.     ideaCipher(YY, YY, EK);    /* repeated encryption */
  432.     memcpy(ZZ, YY, 8);
  433.     for (l = 0; l < BLOCKS; l++)
  434.     ideaCipher(ZZ, ZZ, DK);    /* repeated decryption */
  435.     end = clock() - start;
  436. /* gjm:
  437.  * on systems (like RISC OS) where CLOCKS_PER_SEC is <1000,
  438.  * the original of the following code (with 1000 for 1000.
  439.  * in three places) would give an FP exception.
  440.  */
  441.     l = end / (CLOCKS_PER_SEC / 1000.) + 1;    /* gjm: avoid FP lossage */
  442.     i = l / 1000;
  443.     j = l % 1000;
  444.     l = (16 * BLOCKS * (CLOCKS_PER_SEC / 1000.)) / (end / 1000.);
  445.                         /* gjm: avoid FP lossage */
  446.     printf("%d.%03d seconds = %ld bytes per second\n", i, j, l);
  447.  
  448.     printf("\nX %3u  %3u  %3u  %3u  %3u  %3u  %3u %3u\n",
  449.        XX[0], XX[1], XX[2], XX[3], XX[4], XX[5], XX[6], XX[7]);
  450.     printf("\nY %3u  %3u  %3u  %3u  %3u  %3u  %3u %3u\n",
  451.        YY[0], YY[1], YY[2], YY[3], YY[4], YY[5], YY[6], YY[7]);
  452.     printf("\nZ %3u  %3u  %3u  %3u  %3u  %3u  %3u %3u\n",
  453.        ZZ[0], ZZ[1], ZZ[2], ZZ[3], ZZ[4], ZZ[5], ZZ[6], ZZ[7]);
  454.  
  455.     /* Now decrypted ZZ should be same as original XX */
  456.     for (k = 0; k < 8; k++)
  457.     if (XX[k] != ZZ[k]) {
  458.         printf("\n\07Error!  Noninvertable encryption.\n");
  459.         exit(-1);        /* error exit */
  460.     }
  461.     printf("\nNormal exit.\n");
  462.     return 0;            /* normal exit */
  463. }                /* main */
  464.  
  465. #endif                /* TEST */
  466.  
  467.  
  468. /*************************************************************************/
  469.  
  470. void ideaCfbReinit(struct IdeaCfbContext *context, byte const *iv)
  471. {
  472.     if (iv)
  473.     memcpy(context->iv, iv, 8);
  474.     else
  475.     fill0(context->iv, 8);
  476.     context->bufleft = 0;
  477. }
  478.  
  479. void ideaCfbInit(struct IdeaCfbContext *context, byte const key[16])
  480. {
  481.     ideaExpandKey(key, context->key);
  482.     ideaCfbReinit(context, 0);
  483. }
  484.  
  485. void ideaCfbDestroy(struct IdeaCfbContext *context)
  486. {
  487.     burn(*context);
  488. }
  489.  
  490. /*
  491.  * Okay, explanation time:
  492.  * Phil invented a unique way of doing CFB that's sensitive to semantic
  493.  * boundaries within the data being encrypted.  One way to phrase
  494.  * CFB en/decryption is to say that you XOR the current 8 bytes with
  495.  * IDEA(previous 8 bytes of ciphertext).  Normally, you repeat this
  496.  * at 8-byte intervals, but Phil decided to resync things on the
  497.  * boundaries between elements in the stream being encrypted.
  498.  *
  499.  * That is, the last 4 bytes of a 12-byte field are en/decrypted using
  500.  * the first 4 bytes of IDEA(previous 8 bytes of ciphertext), but then
  501.  * the last 4 bytes of that IDEA computation are thrown away, and the
  502.  * first 8 bytes of the next field are en/decrypted using
  503.  * IDEA(last 8 bytes of ciphertext).  This is equivalent to using a
  504.  * shorter feedback length (if you're familiar with the general CFB
  505.  * technique) briefly, and doesn't weaken the cipher any (using shorter
  506.  * CFB lengths makes it stronger, actually), it just makes it a bit unusual.
  507.  *
  508.  * Anyway, to accomodate this behaviour, every time we do an IDEA
  509.  * encrpytion of 8 bytes of ciphertext to get 8 bytes of XOR mask,
  510.  * we remember the ciphertext.  Then if we have to resync things
  511.  * after having processed, say, 2 bytes, we refill the iv buffer
  512.  * with the last 6 bytes of the old ciphertext followed by the
  513.  * 2 bytes of new ciphertext stored in the front of the iv buffer.
  514.  */
  515. void ideaCfbSync(struct IdeaCfbContext *context)
  516. {
  517.     int bufleft = context->bufleft;
  518.  
  519.     if (bufleft) {
  520.     memmove(context->iv + bufleft, context->iv, 8 - bufleft);
  521.     memcpy(context->iv, context->oldcipher + 8 - bufleft, bufleft);
  522.     context->bufleft = 0;
  523.     }
  524. }
  525.  
  526. /*
  527.  * Encrypt a buffer of data, using IDEA in CFB mode.
  528.  * There are more compact ways of writing this, but this is
  529.  * written for speed.
  530.  */
  531. void ideaCfbEncrypt(struct IdeaCfbContext *context, byte const *src,
  532.             byte * dest, int count)
  533. {
  534.     int bufleft = context->bufleft;
  535.     byte *bufptr = context->iv + 8 - bufleft;
  536.  
  537.     /* If there are no more bytes to encrypt that there are bytes
  538.      * in the buffer, XOR them in and return.
  539.      */
  540.     if (count <= bufleft) {
  541.     context->bufleft = bufleft - count;
  542.     while (count--) {
  543.         *dest++ = *bufptr++ ^= *src++;
  544.     }
  545.     return;
  546.     }
  547.     count -= bufleft;
  548.     /* Encrypt the first bufleft (0 to 7) bytes of the input by XOR
  549.      * with the last bufleft bytes in the iv buffer.
  550.      */
  551.     while (bufleft--) {
  552.     *dest++ = (*bufptr++ ^= *src++);
  553.     }
  554.     /* Encrypt middle blocks of the input by cranking the cipher,
  555.      * XORing 8-byte blocks, and repeating until the count
  556.      * is 8 or less.
  557.      */
  558.     while (count > 8) {
  559.     bufptr = context->iv;
  560.     memcpy(context->oldcipher, bufptr, 8);
  561.     ideaCipher(bufptr, bufptr, context->key);
  562.     bufleft = 8;
  563.     count -= 8;
  564.     do {
  565.         *dest++ = (*bufptr++ ^= *src++);
  566.     } while (--bufleft);
  567.     }
  568.     /* Do the last 1 to 8 bytes */
  569.     bufptr = context->iv;
  570.     memcpy(context->oldcipher, bufptr, 8);
  571.     ideaCipher(bufptr, bufptr, context->key);
  572.     context->bufleft = 8 - count;
  573.     do {
  574.     *dest++ = (*bufptr++ ^= *src++);
  575.     } while (--count);
  576. }
  577.  
  578.  
  579. /*
  580.  * Decrypt a buffer of data, using IDEA in CFB mode.
  581.  * There are more compact ways of writing this, but this is
  582.  * written for speed.
  583.  */
  584. void ideaCfbDecrypt(struct IdeaCfbContext *context, byte const *src,
  585.             byte * dest, int count)
  586. {
  587.     int bufleft = context->bufleft;
  588.     static byte *bufptr;
  589.     byte t;
  590.  
  591.     bufptr = context->iv + (8 - bufleft);
  592.     if (count <= bufleft) {
  593.     context->bufleft = bufleft - count;
  594.     while (count--) {
  595.         t = *bufptr;
  596.         *dest++ = t ^ (*bufptr++ = *src++);
  597.     }
  598.     return;
  599.     }
  600.     count -= bufleft;
  601.     while (bufleft--) {
  602.     t = *bufptr;
  603.     *dest++ = t ^ (*bufptr++ = *src++);
  604.     }
  605.     while (count > 8) {
  606.     bufptr = context->iv;
  607.     memcpy(context->oldcipher, bufptr, 8);
  608.     ideaCipher(bufptr, bufptr, context->key);
  609.     bufleft = 8;
  610.     count -= 8;
  611.     do {
  612.         t = *bufptr;
  613.         *dest++ = t ^ (*bufptr++ = *src++);
  614.     } while (--bufleft);
  615.     }
  616.     bufptr = context->iv;
  617.     memcpy(context->oldcipher, bufptr, 8);
  618.     ideaCipher(bufptr, bufptr, context->key);
  619.     context->bufleft = 8 - count;
  620.     do {
  621.     t = *bufptr;
  622.     *dest++ = t ^ (*bufptr++ = *src++);
  623.     } while (--count);
  624. }
  625.  
  626. /********************************************************************/
  627.  
  628. /*
  629.  * Cryptographically strong pseudo-random-number generator.
  630.  * The design is from Appendix C of ANSI X9.17, "Financial
  631.  * Institution Key Management (Wholesale)", with IDEA
  632.  * substituted for the DES.
  633.  */
  634.  
  635. /*
  636.  * Initialize a cryptographic random-number generator.
  637.  * key and seed should be arbitrary.
  638.  */
  639. void ideaRandInit(struct IdeaRandContext *context, byte const key[16],
  640.           byte const seed[8])
  641. {
  642.     int i;
  643.  
  644.     ideaExpandKey(key, context->key);
  645.     context->bufleft = 0;
  646.     memcpy(context->internalbuf, seed, 8);
  647. }
  648.  
  649.  
  650. /*
  651.  * Read out the RNG's state.
  652.  */
  653. void ideaRandState(struct IdeaRandContext *context, byte key[16], byte seed[8])
  654. {
  655.     int i;
  656.  
  657.     memcpy(seed, context->internalbuf, 8);
  658.     for (i = 0; i < 8; i++) {
  659.     key[2 * i] = context->key[i] >> 8;
  660.     key[2 * i + 1] = context->key[i];
  661.     }
  662.  
  663. }
  664.  
  665. /*
  666.  * Encrypt the RNG's state with the given CFB encryptor.
  667.  */
  668. void ideaRandWash(struct IdeaRandContext *context, struct IdeaCfbContext *cfb)
  669. {
  670.     byte keyseed[16 + 8];
  671.     int i;
  672.  
  673.     ideaRandState(context, keyseed, keyseed + 16);
  674.     ideaCfbEncrypt(cfb, keyseed, keyseed, 16 + 8);
  675.     ideaRandInit(context, keyseed, keyseed + 16);
  676.  
  677.     memset(keyseed, 0, 16 + 8);
  678. }
  679.  
  680. /*
  681.  * Cryptographic pseudo-random-number generator, used for generating
  682.  * session keys.
  683.  */
  684. byte
  685. ideaRandByte(struct IdeaRandContext *c)
  686. {
  687.     int i;
  688.  
  689.     if (!c->bufleft) {
  690.     byte timestamp[8];
  691.  
  692.     /* Get some true-random noise to help */
  693.     randPoolGetBytes(timestamp, sizeof(timestamp));
  694.  
  695.     /* Compute next 8 bytes of output */
  696.     for (i = 0; i < 8; i++)
  697.         c->outbuf[i] = c->internalbuf[i] ^ timestamp[i];
  698.     ideaCipher(c->outbuf, c->outbuf, c->key);
  699.     /* Compute new seed vector */
  700.     for (i = 0; i < 8; i++)
  701.         c->internalbuf[i] = c->outbuf[i] ^ timestamp[i];
  702.     ideaCipher(c->internalbuf, c->internalbuf, c->key);
  703.     burn(timestamp);
  704.     c->bufleft = 8;
  705.     }
  706.     return c->outbuf[--c->bufleft];
  707. }
  708.  
  709. /* end of idea.c */
  710.